package com.tarena.lbs.business.servcie.impl;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.github.pagehelper.PageInfo;
import com.tarena.lbs.activity.pojo.vo.ActivityVO;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.base.protocol.model.Result;
import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.business.dao.repository.StoreChainRepository;
import com.tarena.lbs.business.dao.repository.StoreRepository;
import com.tarena.lbs.business.pojo.param.StoreParam;
import com.tarena.lbs.business.pojo.po.StoreChainPO;
import com.tarena.lbs.business.pojo.param.UserLocationParam;
import com.tarena.lbs.business.pojo.po.StorePO;
import com.tarena.lbs.business.pojo.query.AreaStoreQuery;
import com.tarena.lbs.business.pojo.query.StoreQuery;
import com.tarena.lbs.business.pojo.vo.StoreVO;
import com.tarena.lbs.business.servcie.StoreService;
import com.tarena.lbs.content.api.service.ArticleService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class StoreServiceImpl implements StoreService {
    @Autowired
    private StoreRepository storeRepository;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public void saveUserLocation(UserLocationParam param) {
        log.info("保存用户位置信息：userId={}, latitude={}, longitude={}",
                 param.getUserId(), param.getLatitude(), param.getLongitude());

        // 确保经纬度精度为小数点后5位
        if (param.getLatitude() != null) {
            try {
                double lat = Double.parseDouble(param.getLatitude());
                param.setLatitude(String.format("%.5f", lat));
            } catch (NumberFormatException e) {
                log.error("纬度格式转换失败: {}", e.getMessage());
            }
        }
        if (param.getLongitude() != null) {
            try {
                double lon = Double.parseDouble(param.getLongitude());
                param.setLongitude(String.format("%.5f", lon));
            } catch (NumberFormatException e) {
                log.error("经度格式转换失败: {}", e.getMessage());
            }
        }

        // 构建Redis key
        String redisKey = "user:location";

        // 存储用户定位信息到Redis，设置过期时间为1小时
        redisTemplate.opsForValue().set(redisKey, param, 1, TimeUnit.HOURS);
        log.info("用户位置信息保存成功，key={}, 格式化后经纬度: ({}, {})",
                 redisKey, param.getLatitude(), param.getLongitude());
    }

    @Autowired
    private StoreChainRepository storeChainRepository;
    @DubboReference
    private ArticleService articleService;

    @Override
    public void addStore(StoreParam param) throws BusinessException {
        StorePO po = assembleBusinessPO(param);
        StorePO po1 = storeRepository.saveStore(po);

        //生成二維碼
        StoreChainPO cPo = new StoreChainPO();
        cPo.setStoreId(po1.getId());
        UUID uuid = UUID.randomUUID();
        String linke = "https://store.example.com/store?store=store"+uuid.toString().replace("-", "");
        cPo.setLink(linke);
        cPo.setLinkImage(po1.getStoreLogo());
        cPo.setLinkStatus(0);
        cPo.setBusinessId(po1.getBusinessId());
        cPo.setCreateTime(new Date());
        storeChainRepository.saveStoreChain(cPo);
    }

    @Override
    public PageResult<StoreVO> pageList(StoreQuery query) {
        PageResult<StoreVO> voPage = new PageResult<>();
        PageInfo<StorePO> pageInfo = storeRepository.pageList(query);
        // 将分页信息中的页码设置到分页结果对
        voPage.setPageNo(pageInfo.getPageNum());
        // 将分页信息中的每页数量设置到分页结果对象中
        voPage.setPageSize(pageInfo.getPageSize());
        // 将分页信息中的总记录数设置到分页结果对象中
        voPage.setTotal(pageInfo.getTotal());

        List<StoreVO> vos = null;
        List<StorePO> pos = pageInfo.getList();
        if (CollectionUtils.isNotEmpty(pos)) {
            vos = pos.stream().map(po -> {
                StoreVO vo = new StoreVO();
                BeanUtils.copyProperties(po, vo);
                return vo;
            }).collect(Collectors.toList());
        }
        voPage.setObjects(vos);
        return voPage;
    }

    @Override
    public void updateStore(StoreParam param) throws BusinessException {
            StorePO po = assembleBusinessPO(param);
            storeRepository.updateById(po);
    }

    @Override
    public void deleteStore(Long id) {
        storeRepository.deleteById(id);
    }

    @Override
    public StoreVO storeEdit(Integer id) {
        StorePO storePO = storeRepository.storeEdit(id);
        if (storePO == null) {
            // 根据业务需求，可以选择抛出异常或返回null
            throw new RuntimeException("未找到ID为 " + id + " 的店铺");
            // 或者 return null;
        }
        StoreVO storeVO = new StoreVO();
        BeanUtils.copyProperties(storePO, storeVO);
        return storeVO;
    }


    @Override
    public List<StoreVO> getStoreByCity(AreaStoreQuery query) {
        // 调用 storeRepository 的 getStoreByCity 方法查询符合条件的店铺持久化对象列表
        List<StorePO> pos = storeRepository.getStoreByCity(query);
        // 声明一个存储店铺视图对象的列表
        List<StoreVO> vos = null;
        // 判断持久化对象列表是否不为空
        if (CollectionUtils.isNotEmpty(pos)){
            vos=pos.stream().map(po->{
                StoreVO vo = new StoreVO();
                BeanUtils.copyProperties(po,vo);
                return vo;
            }).collect(Collectors.toList());
        }
        return vos;
    }


    @Override
    public Result<Map<String, Integer>> getStoreAndArticle() {
        Map<String, Integer> map = new HashMap<>();
        List<StorePO> storeVOList = storeRepository.getStoreList();
        for (StorePO storePO : storeVOList){
            Integer count =articleService.findArticles(storePO.getId());
            map.put(storePO.getStoreName(), count);
        }
        log.info("map:{}",map);
        return new Result<>(map);
    }




    @Override
    public List<ActivityVO> getActivity(@PathVariable("id") Integer id) {
        return storeRepository.getActivity(id);
    }

    /**
     * 页面参数转换数据库实体类
     *
     * @param param
     * @return
     */
    private StorePO assembleBusinessPO(StoreParam param) {
        StorePO po = new StorePO();
        BeanUtils.copyProperties(param, po);
        if(param.getId()==null){
            //创建时间
            po.setCreateTime(new Date());
        }
        po.setUpdateTime(new Date());
        if (param.getStoreImagesIds()!=null && !param.getStoreImagesIds().isEmpty()) {
            List<String> ids = param.getStoreImagesIds();
            String images = ids.stream().collect(Collectors.joining(","));
            po.setStoreImagesId(images);
        }
        return po;
    }

}